<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="queryData" layout="inline">
            <a-form-item v-if="id == 1 && permissionStore.hasPermisson('yllb.cx')" label="原料类别">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                       v-model="pageData.dropDownData" @press-enter="huiche"/>
            </a-form-item>
            <a-form-item v-if="id == 2 && permissionStore.hasPermisson('ylsx.cx')" label="原料属性">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                       v-model="pageData.materialsCategoryAttributes" @press-enter="huiche2"/>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar :items="pageData.btnList" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                   @export="exportExcel" @import="importHandler" @excel="downloadHandler">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
      <!-- <div class="my-tool-bar">
                <Toolbar :items="pageData.btnList" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                    @export="exportExcel" @import="importHandler" @excel="downloadHandler">
                </Toolbar>
            </div> -->
    </template>
    <template #pageTabel>
      <a-tabs   :lazy-load="true" :justify="true" default-active-key="1" @change="handoff">
        <template #extra>
          <Toolbar style="position: absolute;right: 0;" :items="tabBtnList" @import="importHandler"
                   @excel="downloadHandler">
          </Toolbar>
        </template>
        <a-tab-pane title="原料类别" key="1">
          <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
              <div style="width: 100%; height: 100%">
                <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"></encapsulation-agrid>
              </div>
          </a-spin>
        </a-tab-pane>
        <a-tab-pane title="原料属性" key="2">
          <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
              <div style="width: 100%; height: 100%">
                <encapsulation-agrid ref="table2Ref" :configaggrid="configTable2"></encapsulation-agrid>
              </div>
          </a-spin>
        </a-tab-pane>
      </a-tabs>
    </template>
    <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }"
              :mask-closable="false"
              :width="400" :visible="pageData.showAdd" unmountOnClose @ok="sideOk" @cancel="sideNo">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item label-col-flex="80px" v-if="id == 1" label="原料类别" field="materialsCategoryName"
                       :rules="[{ required: true, message: '原料类别必填' }]" :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" placeholder="" v-model="dataForm.materialsCategoryName"/>
          </a-form-item>

          <a-form-item label-col-flex="80px" v-if="id == 2" label="编号" field="rawmaterialAttributeCode"
                       :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
                       :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" placeholder="" @blur="inputBlur1"
                     v-model.trim="dataForm.rawmaterialAttributeCode"/>
          </a-form-item>
          <a-form-item label-col-flex="80px" v-if="id == 2" label="原料属性" field="materialsAttribute"
                       :rules="[{ required: true, message: '原料属性必填' }]" :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" placeholder="" v-model="dataForm.materialsAttribute"/>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="备注" field="remark">
            <!-- <a-input v-model="dataForm.remark"/> -->
            <a-textarea class="bacClass" placeholder="" v-model="dataForm.remark" :max-length="400" allow-clear
                        show-word-limit/>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
import {baseURL} from '../../../api/axios.config'
import {post} from '@/api/http'
import {useTable, useRowKey, useTableColumn, usePagination, useRowSelection} from '@/hooks/table'
import axios from 'axios'
import emitter from '@/hooks/useEventBus'
import {ref, reactive, onMounted, toRefs} from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import {Form, Message, Modal} from '@arco-design/web-vue'
import {FormInstance} from '@arco-design/web-vue/es/form'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'

import {localeText} from '@/api/aggridZw'
import {pagingList} from '@/api/paging'
import {simplifyMessages} from '@/api/messageSimplification'
import {exportStyleExcel} from '@/api/Export2StyleExcel'
import {saveOrUpdateGridState as saveOrUpdateGridState01} from '@/hooks/useGridState'
import {saveOrUpdateGridState as saveOrUpdateGridState02} from '@/hooks/useGridState'
import useAgGridFilterSelector from '@/utils/aggridFilterAllSelect'

interface Cloth {
  code: string
}

interface ClothInfo {
  code: any
  createTime: any
  isDelete: any
  remark: any
  updateTime: any
  id: any
  materialsCategoryName: any
  materialsCategoryAttribute: any
  updateName: any
  createName: any
  materialsAttribute: any
  materialsCategory: any
  rawmaterialTypeCode: any
  rawmaterialAttributeCode: any
}

export default {
  name: 'Rawmaterialcategory',
  setup() {
    let cxbl = ''
    const selectHandler = () => {
      if (id.value == 1) {
        pagination.page = 1
        cxbl = pageData.dropDownData
        doRefresh()
      } else if (id.value == 2) {
        paginations.page = 1
        cxbl = pageData.materialsCategoryAttributes
        doRefreshs()
      }
    }
    const tableColumns = [
      {
        title: '序号',
        key: 'rawmaterialTypeCode',
        dataIndex: 'rawmaterialTypeCode',
        width: 150,
      },
      {
        title: '原料类别',
        key: 'materialsCategoryName',
        dataIndex: 'materialsCategoryName',
        width: 150,
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 150,
      },
      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        width: 200,
      },
      {
        title: '最后修改人',
        key: 'updateName',
        dataIndex: 'updateName',
        width: 150,
      },
      {
        title: '最后修改时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
        width: 200,
      },
      {
        title: '操作',
        key: 'edit',
        dataIndex: 'edit',
        width: 150,
        slotName: 'edit',
        fixed: 'right',
      },
    ]
    const tableColumns2 = [
      {
        title: '序号',
        key: 'serialNo',
        dataIndex: 'serialNo',
        width: 150,
      },
      {
        title: '编号',
        key: 'rawmaterialAttributeCode',
        dataIndex: 'rawmaterialAttributeCode',
        width: 150,
      },
      {
        title: '原料属性',
        key: 'materialsAttribute',
        dataIndex: 'materialsAttribute',
        width: 150,
      },
      // {
      //     title: "原料类别",
      //     key: "materialsCategory",
      //     dataIndex: "materialsCategory",
      //     width: 150,
      // },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 150,
      },

      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        width: 200,
      },
      {
        title: '最后修改人',
        key: 'updateName',
        dataIndex: 'updateName',
        width: 150,
      },
      {
        title: '最后修改时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
        width: 200,
      },
      {
        title: '操作',
        key: 'edit',
        dataIndex: 'edit',
        width: 150,
        slotName: 'edit',
        fixed: 'right',
      },
    ]
    let tc: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      obj['width'] = 250
      if (o.slotName === 'edit') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 90
        obj['cellRenderer'] = {
          template: `
            <a-tag class="tagCss" v-if="e" @click="a">修改</a-tag>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            return {
              e: pageData.isEdit,
              a,
            }
          },
        }
      }

      return obj
    })
    let tc2: any[] = tableColumns2.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      obj['width'] = 250
      if (o.slotName === 'edit') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 90
        obj['cellRenderer'] = {
          template: `
            <a-tag class="tagCss" :disabled="e" @click="a">修改</a-tag>`,
          setup(props: any) {
            const a = () => {
              editHandler1(props.params.data)
            }
            return {
              e: !pageData.isEdit,
              a,
            }
          },
        }
      }

      return obj
    })
    tc.unshift({
      showRowGroup: 'hide_def',
      headerName: "",
      "checkboxSelection": true,
      "headerCheckboxSelection": true,
      "pinned": "left",
      "width": 50,
      resizable: false,
      filter: false,
      sortable: false,
      minWidth: 50,
      maxWidth: 50,
      lockPosition: "left",
    })
    tc2.unshift({
      showRowGroup: 'hide_def',
      headerName: "",
      "checkboxSelection": true,
      "headerCheckboxSelection": true,
      "pinned": "left",
      "width": 50,
      resizable: false,
      filter: false,
      sortable: false,
      minWidth: 50,
      maxWidth: 50,
      lockPosition: "left",
    })
    const table1Ref: any = ref(null)
    let configTable1 = {
      url: 'product/RawmaterialType/select', //接口路径
      queryData: {
        //接口参数
        deleteState: 0,
        materialsCategoryName: cxbl
      },
      paginationShow: true, //分页是否显示
      invokeiIterface: true, //是否调用接
      rowMultiSelectWithClick: true, //点击行是否多选
      column: tc,
      fileName: 'Rawmaterialcategory-1'
    }
    const table2Ref: any = ref(null)
    let configTable2 = {
      url: 'product/RawmaterialAttribute/select', //接口路径
      queryData: {
        //接口参数
        deleteState: 0,
        materialsAttribute: cxbl,
      },
      paginationShow: true, //分页是否显示
      invokeiIterface: true, //是否调用接
      rowMultiSelectWithClick: true, //点击行是否多选
      column: tc2,
      fileName: 'Rawmaterialcategory-2'
    }
    const aggridFs = useAgGridFilterSelector()

    function PageSize(val: any) {
      if (id.value == 1) {
        pagination.page = val
        doRefresh()
      } else if (id.value == 2) {
        paginations.page = val
        doRefreshs()
      }
    }

    function change1(val: any) {
      if (id.value == 1) {
        pagination.pageSize = val
        doRefresh()
      } else if (id.value == 2) {
        paginations.pageSize = val
        doRefreshs()
      }
    }

    const headerShow = ref<boolean>(true)
    let id: any = ref(1)

    function doRefresh() {
      table1Ref.value.setQuery({
        deleteState: 0,
        materialsCategoryName: cxbl
      })
    }

    function doRefreshs() {
      table2Ref.value.setQuery({
        deleteState: 0,
        materialsAttribute: cxbl,
      })
    }

    const {selectedRowKeys, onSelectionChange} = useRowSelection()
    const pagination = usePagination(doRefresh)
    const paginations = usePagination(doRefreshs)
    const table = useTable()
    const rowKey = useRowKey('id')
    const pageData = reactive<{
      clothList: Cloth[]
      showAdd: boolean
      sideTitle: string
      materialsCategory: []
      dropDownData: any
      materialsAttribute: any
      materialsCategoryAttribute: any
      materialsCategoryAttributes: any
      pageLoading: boolean
      rHeight: number | undefined
      btnList: any[]
      isEdit: boolean
    }>({
      clothList: [],
      showAdd: false,
      sideTitle: '新增原料类别',
      materialsCategory: [],
      dropDownData: '',
      materialsAttribute: '',
      materialsCategoryAttribute: '',
      materialsCategoryAttributes: '',
      pageLoading: false,
      rHeight: 0,
      btnList: [],
      isEdit: false,
    })
    //下拉数据
    const focusSel = () => {
      selCxAll({materialsCategoryName: '', deleteState: 0})
    }

    const options = ref<any>(pageData.clothList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        const ob = {materialsCategoryName: value, deleteState: 0}
        loading.value = true
        selCxAll(ob)
        options.value = pageData.clothList
        loading.value = false
      } else {
        options.value = []
      }
    }

    //下拉框查询
    function selCxAll(val: any) {
      post({
        url: 'product/RawmaterialType/getDrop',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          pageData.clothList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    //原料属性 新增修改里的类别下拉框
    const options1 = ref<any>(pageData.materialsCategoryAttribute)
    const loading1 = ref(false)
    const handleSearch1 = (value: any) => {
      if (value) {
        const ob = {materialsAttribute: value, deleteState: 0}
        loading1.value = true
        szTyoeNames(ob)
        options1.value = pageData.materialsCategoryAttribute
        loading1.value = false
      } else {
        options1.value = []
      }
    }
    const szTyoeNames = (value: any) => {
      post({
        url: 'product/RawmaterialAttribute/getAttributeDrop',
        data: value,
      })
          .then(({data, code}: any) => {
            if (code === 200) {
              pageData.materialsCategoryAttribute = data
            }
          })
          .catch(console.log)
    }

    onMounted(() => {
      emitter.on('Rawmaterialcategory', () => {
        doRefresh()
      })
    })
    const queryData = reactive({
      clothType: '',
    })
    const addHandler = () => {
      for (let item in dataForm) {
        dataForm[item] = ''
      }
      pageData.showAdd = true
      if (id.value == 1) {
        pageData.sideTitle = '新增原料类别'
      } else if (id.value == 2) {
        pageData.sideTitle = '新增原料属性'
      }
    }
    const dataForm = reactive<ClothInfo>({
      code: '',
      createTime: '',
      isDelete: '',
      remark: '',
      updateTime: '',
      id: '',
      materialsCategoryName: '',
      materialsCategoryAttribute: '',
      updateName: '',
      createName: '',
      materialsAttribute: '',
      materialsCategory: '',
      rawmaterialTypeCode: '',
      rawmaterialAttributeCode: '',
    })

    // 表格准备事件
    const gridOption = ref()
    const colState = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
      colState.value = params.columnApi
      //gridOption.value.sizeColumnsToFit();
    }

    const gridOption2 = ref()
    const colState2 = ref()
    const gridReady2 = (params: any) => {
      gridOption2.value = params.api
      colState2.value = params.columnApi
      // gridOption2.value.sizeColumnsToFit();
    }

    const formRef = ref<FormInstance>()
    const sideOk = () => {
      // szTyoeNames({})
      if (id.value == 1) {
        let dataFroms = {
          id: dataForm.id,
          materialsCategoryName: dataForm.materialsCategoryName,
          materialsCategoryAttribute: dataForm.materialsCategoryAttribute,
          // rawmaterialTypeCode: dataForm.rawmaterialTypeCode,
          remark: dataForm.remark,
        }
        formRef.value?.validate().then((err) => {
          if (!err) {
            pageData.pageLoading = true

            if (pageData.sideTitle === '新增原料类别') {
              dataFroms.id = null
              post({
                url: 'product/RawmaterialType/add',
                data: [dataFroms],
              })
                  .then((res: any) => {
                    if (res.code === 200) {
                      formRef.value?.resetFields()
                      doRefresh()
                      pageData.showAdd = false
                      Message.success({
                        content: '新增成功',
                        duration: 5000,
                      })
                    } else {
                      Message.error({
                        content: res.message,
                        duration: 5000,
                      })
                    }
                  })
                  .finally(() => {
                    pageData.pageLoading = false
                  })
            } else if (pageData.sideTitle === '修改原料类别') {
              post({
                url: 'product/RawmaterialType/update',
                data: [dataFroms],
              })
                  .then((res: any) => {
                    if (res.code === 200) {
                      formRef.value?.resetFields()
                      //修改面料属性后重新渲染table表单
                      doRefresh()
                      pageData.showAdd = false
                      Message.success({
                        content: '修改成功',
                        duration: 5000,
                      })
                    } else {
                      Message.error({
                        content: simplifyMessages(res.message),
                        duration: 5000,
                      })
                    }
                  })
                  .finally(() => {
                    pageData.pageLoading = false
                  })
            }
          }
        })
      } else if (id.value == 2) {
        formRef.value?.validate().then((err) => {
          if (!err) {
            pageData.pageLoading = true

            if (pageData.sideTitle == '新增原料属性') {
              dataForm.id = null
              post({
                url: 'product/RawmaterialAttribute/add',
                data: [dataForm],
              })
                  .then((res: any) => {
                    if (res.code === 200) {
                      // formRef.value?.resetFields()
                      doRefreshs()
                      pageData.showAdd = false
                      Message.success({
                        content: '新增成功',
                        duration: 5000,
                      })
                    } else {
                      Message.error({
                        content: res.message,
                        duration: 5000,
                      })
                    }
                  })
                  .finally(() => {
                    pageData.pageLoading = false
                  })
            } else if (pageData.sideTitle == '修改原料属性') {
              let dataForms = {
                id: dataForm.id,
                materialsAttribute: dataForm.materialsAttribute,
                materialsCategory: dataForm.materialsCategory,
                rawmaterialAttributeCode: dataForm.rawmaterialAttributeCode,
                remark: dataForm.remark,
              }
              post({
                url: 'product/RawmaterialAttribute/update',
                data: [dataForms],
              })
                  .then((res: any) => {
                    if (res.code === 200) {
                      // formRef.value?.resetFields()
                      doRefreshs()
                      pageData.showAdd = false
                      Message.success({
                        content: '修改成功',
                        duration: 5000,
                      })
                    } else {
                      Message.error({
                        content: res.message,
                        duration: 5000,
                      })
                    }
                  })
                  .finally(() => {
                    pageData.pageLoading = false
                  })
            }
          }
        })
      }
    }
    const sideNo = () => {
      pageData.showAdd = false
    }
    const deleteHandler = () => {
      if (id.value == 1 && table1Ref.value.getSelectedRows().length == 0) {
        Message.error('请先勾选')
        return
      }
      if (id.value == 2 && table2Ref.value.getSelectedRows().length == 0) {
        Message.error('请先勾选')
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          pageData.pageLoading = true
          if (id.value == 1) {
            post({
              url: 'product/RawmaterialType/deleteZT',
              data: table1Ref.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            })
                .then(({code, message}: any) => {
                  if (code === 200) {
                    pagination.page = 1
                    doRefresh()
                    selectedRowKeys.value = []
                    Message.success({
                      content: '删除成功',
                      duration: 5000,
                    })
                  } else {
                    Message.error({
                      content: simplifyMessages(message),
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
          } else if (id.value == 2) {
            post({
              url: 'product/RawmaterialAttribute/deleteZT',
              data: table2Ref.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            })
                .then(({code, message}: any) => {
                  if (code === 200) {
                    selectedRowKeys.value = []
                    paginations.page = 1
                    doRefreshs()
                    Message.success({
                      content: '删除成功',
                      duration: 5000,
                    })
                  } else {
                    Message.error({
                      content: message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
          }
        },
      })
    }
    const editHandler = (record: any) => {
      dataForm.id = Number(record.id)
      dataForm.rawmaterialTypeCode = record.rawmaterialTypeCode
      dataForm.materialsCategoryAttribute = record.materialsCategoryAttribute
      dataForm.materialsCategoryName = record.materialsCategoryName
      dataForm.remark = record.remark
      //侧滑栏滑出滑入
      pageData.showAdd = true
      pageData.sideTitle = '修改原料类别'
    }
    const editHandler1 = (record: any) => {
      dataForm.id = record.id
      dataForm.rawmaterialAttributeCode = record.rawmaterialAttributeCode
      dataForm.materialsAttribute = record.materialsAttribute
      dataForm.materialsCategory = record.materialsCategory
      dataForm.remark = record.remark

      //侧滑栏滑出滑入
      pageData.showAdd = true
      pageData.sideTitle = '修改原料属性'
    }
    let tableList1 = ref([])
    let tableList2 = ref([])
    const handoff = (key: any) => {
      id.value = key
      if (id.value == 1) {
        doRefresh()

      } else {
        doRefreshs()
      }
    }
    const isChiese = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
          cb('填写的值只能是英文数字组合或英文，数字！')
        }
        resolve()
      })
    }
    const inputBlur = () => {
      dataForm.rawmaterialTypeCode = dataForm.rawmaterialTypeCode.toUpperCase()
    }
    const inputBlur1 = () => {
      dataForm.rawmaterialAttributeCode = dataForm.rawmaterialAttributeCode.toUpperCase()
    }


    //前端导出
    function exportExcel() {
      if (id.value == 1 && table1Ref.value.getSelectedRows().length == 0) {
        Message.error('请先勾选需导出行数据！')
        return
      }
      if (id.value == 2 && table2Ref.value.getSelectedRows().length == 0) {
        Message.error('请先勾选需导出行数据！')
        return
      }
      let header: any = []
      let filterVal: any = []
      let data: any = []
      if (id.value == 1) {
        header = ['序号', '原料类别', '备注', '创建人', '创建时间', '最后修改人', '最后修改时间']
        filterVal = ['rawmaterialTypeCode', 'materialsCategoryName', 'remark', 'createName', 'createTime', 'updateName', 'updateTime']
        data = formatJson(filterVal, table1Ref.value.getSelectedRows());
        exportStyleExcel({header, data, filename: "原料类别.xlsx"})
      } else if (id.value == 2) {
        header = ['序号', '编号', '原料属性', '备注', '创建人', '创建时间', '最后修改人', '最后修改时间']
        filterVal = ['serialNo', 'rawmaterialAttributeCode', 'materialsAttribute', 'remark', 'createName', 'createTime', 'updateName', 'updateTime']
        data = formatJson(filterVal, table2Ref.value.getSelectedRows());
        exportStyleExcel({header, data, filename: "原料属性.xlsx"})
      }
    }

    function formatJson(filterVal: any[], jsonData: any[]) {
      return jsonData.map(v => filterVal.map(j => {
        if (v[j]) {
          return v[j];
        } else {
          return '';
        }
      }))
    }


    //模板下载
    const downloadHandler = () => {
      if (id.value == 1) {
        axios
            .get(baseURL + '/product/RawmaterialType/uploadRawmaterialTypeModel', {
              responseType: 'blob',
              headers: {
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((res) => {
              if (res.status === 200) {
                filedownload(res.data, '原料类别.xlsx')
              }
            })
      } else {
        axios
            .get(baseURL + '/product/RawmaterialAttribute/uploadRawmaterialAttributeModel', {
              responseType: 'blob',
              headers: {
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((res) => {
              if (res.status === 200) {
                filedownload(res.data, '原料属性.xlsx')
              }
            })
      }
    }
    const importHandler = () => {
      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
          formData.append('file', inputEle.files[0] || '')
        } else {
          Message.warning('未选择文件！')
          return
        }
        pageData.pageLoading = true
        if (id.value == 1) {
          // 原料类别
          axios
              .post(baseURL + '/product/RawmaterialType/analyseRawmaterialTypeModel', formData, {
                headers: {
                  'Content-Type': 'multipart/form-data',
                  token: sessionStorage.getItem('USER-TOKEN-KEY'),
                },
              })
              .then((result) => {
                if (result.data['code'] === 200) {
                  Message.success('导入成功')
                } else {
                  Message.error(result.data.message)
                }
              })
              .finally(() => {
                pageData.pageLoading = false
                doRefresh()
              })
        } else {
          // 原料属性
          axios
              .post(
                  baseURL + '/product/RawmaterialAttribute/analyseRawmaterialAttributeModel',
                  formData,
                  {
                    headers: {
                      'Content-Type': 'multipart/form-data',
                      token: sessionStorage.getItem('USER-TOKEN-KEY'),
                    },
                  }
              )
              .then((result) => {
                if (result.data['code'] === 200) {
                  Message.success('导入成功')
                } else {
                  Message.error(result.data.message)
                }
              })
              .finally(() => {
                pageData.pageLoading = false
                doRefreshs()
              })
        }
      })
      inputEle.click()
    }

    function windowsOpen() {
      window.open()
    }

    const handleSearchs = () => {
      selCxAll({
        materialsCategoryName: '',
        deleteState: 0,
      })
    }
    const handleSearchs1 = () => {
      szTyoeNames({
        materialsAttribute: '',
        deleteState: 0,
      })
    }
    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()
    const tabBtnList = ref<any>([])
    //yllb 原料类别权限  ylsx原料属性
    //判断是否是当前页
    if (id.value == 1) {
      pageData.btnList = []
      pageData.isEdit = false
      if (permissionStore.hasPermisson('yllb.cx')) {
        pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('yllb.xz')) {
        pageData.btnList.push('新增')
      }
      if (permissionStore.hasPermisson('yllb.sc')) {
        pageData.btnList.push('删除')
      }
      if (permissionStore.hasPermisson('yllb.dc')) {
        pageData.btnList.push('导出')
      }
      if (permissionStore.hasPermisson('yllb.dr')) {
        tabBtnList.value.push('导入')
      }
      if (permissionStore.hasPermisson('yllb.mbxz')) {
        tabBtnList.value.push('模板下载')
      }
      if (permissionStore.hasPermisson('yllb.xg')) {
        pageData.isEdit = true
      }
    } else {
      pageData.btnList = []
      pageData.isEdit = false
      if (permissionStore.hasPermisson('ylsx.cx')) {
        pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('ylsx.xz')) {
        pageData.btnList.push('新增')
      }
      if (permissionStore.hasPermisson('ylsx.sc')) {
        pageData.btnList.push('删除')
      }
      if (permissionStore.hasPermisson('ylsx.dc')) {
        pageData.btnList.push('导出')
      }
      if (permissionStore.hasPermisson('ylsx.dr')) {
        tabBtnList.value.push('导入')
      }
      if (permissionStore.hasPermisson('ylsx.mbxz')) {
        tabBtnList.value.push('模板下载')
      }
      if (permissionStore.hasPermisson('ylsx.xg')) {
        pageData.isEdit = true
      }
    }
    const handleChange = (_data: any) => {
      if (id.value == 1) {
        tableList1 = _data
      } else {
        tableList2 = _data
      }
      table.handleSuccess(_data)
    }


    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]

    tc = a.concat(tc)
    tc2 = a.concat(tc2)
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    const defaultColDef2 = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    const localeText1: any = ref(localeText)
    const huiche = () => {
      pagination.page = 1
      cxbl = pageData.dropDownData
      doRefresh()
    }
    const huiche2 = () => {
      paginations.page = 1
      cxbl = pageData.materialsCategoryAttributes
      doRefreshs()
    }
    const pagingList1: any = ref(pagingList)
    return {
      colState,
      colState2,
      tabBtnList,
      pagingList1,
      huiche,
      huiche2,
      localeText1,
      defaultColDef,
      defaultColDef2,
      tc,
      tc2,
      PageSize,
      change1,
      handleSearchs1,
      handleSearchs,
      importHandler,
      downloadHandler,
      exportExcel,
      isChiese,
      inputBlur,
      inputBlur1,
      selectHandler,
      editHandler1,
      id,
      tableColumns2,
      handoff,
      editHandler,
      sideNo,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      options,
      loading,
      handleSearch,
      options1,
      loading1,
      handleSearch1,
      paginations,
      focusSel,
      handleChange,
      headerShow,
      gridReady,
      gridReady2,
      permissionStore,
      aggridFs,
      table1Ref,
      configTable1,
      table2Ref,
      configTable2,
    }
  },
  components: {Toolbar, },
}
</script>
<style scoped lang="less"></style>